package org.xxpay.pay.channel.jfpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.PayDigestUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 支付回调
 */
@Service
public class JfpayPayNotifyService extends BasePayNotify {

    private static final MyLog _log = MyLog.getLog(JfpayPayNotifyService.class);
    private static final String logPrefix = "【处理"+ JfpayConfig.CHANNEL_NAME+"支付回调】";


    @Override
    public String getChannelName() {
        return JfpayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {
        _log.info("====== 开始处理{}支付回调通知 ======", JfpayConfig.CHANNEL_NAME);
        HttpServletRequest request = (HttpServletRequest) notifyData;
        JSONObject retObj = buildRetObj();
        Map<String, String> payContext = new HashMap();

        String respString = JfpayConfig.RETURN_VALUE_ERROR;
        try {
            PayOrder payOrder = verifyPayParams(request, payContext);
            if( payOrder == null ) { //验证参数失败
                retObj.put(PayConstant.RESPONSE_RESULT, JfpayConfig.RETURN_VALUE_ERROR);
                return retObj;
            }
            //订单已经支付完成
            if(payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS || payOrder.getStatus() == PayConstant.PAY_STATUS_COMPLETE){
                retObj.put(PayConstant.RESPONSE_RESULT, JfpayConfig.RETURN_VALUE_SUCCESS);
                return retObj;
            }
            //上游通知 状态
            String channelOrderNo = payContext.get("queryId"); //上游订单号

            int updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId(), channelOrderNo);
            if (updatePayOrderRows != 1) {
                _log.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
                retObj.put(PayConstant.RESPONSE_RESULT, "处理订单失败");
                return retObj;
            }
            _log.error("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
            payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);

            // 业务系统后端通知
            baseNotify4MchPay.doNotify(payOrder, true);
            _log.info("====== 完成处理{}支付回调通知 ======", JfpayConfig.CHANNEL_NAME);
            respString = JfpayConfig.RETURN_VALUE_SUCCESS;
        } catch (Exception e) {
            _log.error(e, logPrefix + "处理异常");
        }
        retObj.put(PayConstant.RESPONSE_RESULT, respString);
        return retObj;
    }

    /**
     * 验证通知参数
     * @return
     */
    private PayOrder verifyPayParams(HttpServletRequest req, Map<String, String> payContext) {

        try {
            // 验证参数是否合法
            String memberid = req.getParameter("memberid");         // 商户编号
            String orderid = req.getParameter("orderid");           // 订单号
            String amount = req.getParameter("amount");         // 订单金额
            String transactionId = req.getParameter("transaction_id");         // 交易流水号
            String datetime = req.getParameter("datetime");         // 交易时间
            String returncode = req.getParameter("returncode");         //交易状态
            String attach = req.getParameter("attach");         // 扩展返回 不参与签名
            String sign = req.getParameter("sign");         // 签名

            _log.info("{}memberid={}, orderid={}, amount={}, transactionId={}, datetime={}, returncode={}, attach={}, sign={}" ,
                    logPrefix, memberid, orderid, amount, transactionId, datetime, returncode ,attach, sign);

            if(StringUtils.isAnyEmpty(orderid, memberid, amount, sign)){
                _log.error("{}orderid={}, memberid={}, amount={}, sign={}", logPrefix, orderid, memberid, amount, sign);
                return null;
            }

            if(!"00".equals(returncode)) {
                _log.info("[{}]:orderid={} 返回失败", getChannelName(), orderid);
                return null;
            }

            PayOrder payOrder = commonService.payOrderService.findByPayOrderId(orderid); // 根据orderid查单
            if(payOrder == null){
                _log.error("{}订单不存在orderNo={}", logPrefix, orderid);
                return null;
            }

            JfpayConfig dtpayConfig = new JfpayConfig(getPayParam(payOrder));

            Map<String, String> params = new HashMap<>();
            params.put("memberid", memberid);
            params.put("orderid", orderid);
            params.put("amount", amount);
            params.put("transaction_id", transactionId);
            params.put("datetime", datetime);
            params.put("returncode", returncode);

            String myselfSign = PayDigestUtil.getSign(params, dtpayConfig.getApiKey());

            if(!myselfSign.equals(sign)){
                _log.error("{}验签失败", logPrefix);
                return null;
            }

            payContext.put("queryId", transactionId);
            return payOrder;
        } catch (Exception e) {
            _log.error("验证响应数据异常", e);
        }

        return null;

    }
}
